﻿//License:  New BSD License (BSD)
//Copyright (c) 2010, Jesper Lund Stocholm
//All rights reserved.

//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

//* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

//* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

//* Neither the name of Jesper Lund Stocholm nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using IS29500Validator.Models;

using log4net;

namespace IS29500Validator.Utils
{
    /// <summary>
    /// Encapsulates various XML-related functions
    /// </summary>
    public class Xml
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Xml));

        /// <summary>
        /// Load the mapping between ContentTypes and RelationshipTypes
        /// </summary>
        /// <returns>A dictionary based on ContentType</returns>
        public static Dictionary<string, ContentTypeRelationshipMap> LoadXmlMapping()
        {
            // Get location of mapping file
            var mappingFilePath = ConfigurationManager.AppSettings["MappingFileLocation"];
            var xDocument = XDocument.Load(mappingFilePath);

            var dict = new Dictionary<string, ContentTypeRelationshipMap>();

            // Loop through noded in XML-file and convert each to a "ContentTypeRelationshipMap object
            var query = from d in xDocument.Descendants("MapData")
                        select new ContentTypeRelationshipMap()
                        {
                            Clause = d.Element("Clause").Value,
                            ContentType = d.Element("ContentType").Value,
                            NamespaceName = d.Element("NamespaceName").Value,
                            RelationshipType = d.Element("RelationshipType").Value,
                            SchemaName = d.Element("SchemaName").Value,
                        };

            foreach (var item in query)
            {
                // Add each instance to dictionary
                dict.Add(item.ContentType, item);
            }

            // return dictionary
            return dict;
        }

        /// <summary>
        /// Loads all necessary schemas
        /// </summary>
        /// <returns>A set of schemas to validate against</returns>
        public static XmlSchemaSet LoadSchemaSet()
        {
            var xmlSchemaSet = new XmlSchemaSet();

            // Get location of schemas
            string folderPath = ConfigurationManager.AppSettings["SchemaLocation"];

            var directoryDataT = new DirectoryInfo(folderPath);
            var fileT = directoryDataT.GetFiles("*.xsd", SearchOption.AllDirectories);
            foreach (var fileInfo in fileT)
            {
                // Open each schema file
                using (var xmlReader = XmlReader.Create(File.OpenRead(fileInfo.FullName)))
                {
                    // Add file to schema set
                    xmlSchemaSet.Add(null, xmlReader);

                    xmlReader.Close();
                }
            }

            log.InfoFormat("Successfully added {0} schemas to schema set.", fileT.Length);

            

            // Return schemas
            return xmlSchemaSet;
        }
    }
}
